package com.bootcamp.mall.service.order;

import com.bootcamp.mall.dao.GoodsDao;
import com.bootcamp.mall.dao.OrderDao;
import com.bootcamp.mall.dao.UserDao;
import com.bootcamp.mall.model.Order;
import com.bootcamp.mall.model.Spec;
import com.bootcamp.mall.model.User;
import com.bootcamp.mall.model.bo.order.*;
import com.bootcamp.mall.model.vo.order.*;
import com.bootcamp.mall.utils.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: mall
 * @description:
 * @author: Keyu Li
 * @create: 2021-11-11 17:32
 **/

public class OrderServiceImpl implements OrderService {
    @Override
    public OrderByPageVO orderByPage(OrderByPageBO orderByPageBO) {
        // mybatis 查询四连
        SqlSession sqlsession = MyBatisUtil.getSqlsession();
        OrderDao mapper = sqlsession.getMapper(OrderDao.class);
        // 获取总数
        int total = mapper.selectAllOrdersCount(orderByPageBO);
        // 获取vo
        List<OrdersOfOrderByPageVO> orderOfOrderByPageVOS = mapper.selectOrdersByPage(orderByPageBO);
        OrderByPageVO orderByPageVO = new OrderByPageVO();
        orderByPageVO.setOrders(orderOfOrderByPageVOS);
        orderByPageVO.setTotal(total);
        // close
        sqlsession.close();
        return orderByPageVO;
    }

    @Override
    public ShowOrderVO showOrder(Integer id) {
        // 新建vo对象

        // sql查询其他项
        SqlSession sqlsession = MyBatisUtil.getSqlsession();
        OrderDao mapper = sqlsession.getMapper(OrderDao.class);
        // 得到大部分字段
        ShowOrderVO showOrderVO = mapper.selectOrderById(id);
        // 通过goodsId 查询spec列表
        GoodsDao mapperGoods = sqlsession.getMapper(GoodsDao.class);
        List<Spec> specs = mapperGoods.selectSpecIDAndNameAndPriceByGoodsId(showOrderVO.getGoodsId());
        // close
        sqlsession.close();
        // 因为response中没有goodsId这一项，置为null
        // 实际证明：没有置为null也没有关系
        // spec赋值
        showOrderVO.setSpec(specs);
        // 状态列表赋值
        List<StateVO> stateVOS = new ArrayList<>();
        stateVOS.add(new StateVO(0, "未付款"));
        stateVOS.add(new StateVO(1, "未发货"));
        stateVOS.add(new StateVO(2, "已发货"));
        stateVOS.add(new StateVO(3, "已完成订单"));
        showOrderVO.setStates(stateVOS);
        return showOrderVO;
    }

    @Override
    public Integer changeOrder(ChangeOrderBO changeOrderBO) {
        // sqlsession,mapper,method,close,trycatch commit, rollback七联
        SqlSession sqlsession = MyBatisUtil.getSqlsession();
        GoodsDao mapperGoods = sqlsession.getMapper(GoodsDao.class);
        OrderDao mapperOrder = sqlsession.getMapper(OrderDao.class);
        try {
            // 先通过specid查询spec表获取 unitprice
            BigDecimal unitprice = mapperGoods.selectSpecUnitPriceById(changeOrderBO.getSpec());
            // 计算总价，放入bo
            int num = changeOrderBO.getNum();
            changeOrderBO.setAmount(unitprice.multiply(new BigDecimal(num)));
            // 将bo传入sql进行update
            int affectRows = mapperOrder.updateOrder(changeOrderBO);
            if (affectRows == 0)
                throw new Exception();
            sqlsession.commit();
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            sqlsession.rollback();
            return -1;
        } finally {
            sqlsession.close();
        }
    }

    @Override
    public Integer deleteOrder(Integer id) {
        // sql七连
        SqlSession sqlsession = MyBatisUtil.getSqlsession();
        OrderDao mapper = sqlsession.getMapper(OrderDao.class);
        try {
            Integer affectRows = mapper.deleteOrderById(id);
            System.out.println("成功删除订单数：" + affectRows);
            sqlsession.commit();
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            sqlsession.rollback();
            return -1;
        } finally {
            sqlsession.close();
        }
    }

    @Override
    public Integer addOrder(AddOrderBO addOrderBO) {

        // 根据 token(nickname)获取 userid,nickname，recipient, address, phone
        // 根据 goodDetailId(SpecId)获取specName, goodsId, goodsName, unitPrice
        // 根据 createTime自动生成 createTime
        // 插入到order表当中

        // sql七连
        SqlSession sqlsession = MyBatisUtil.getSqlsession();
        OrderDao mapperOrder = sqlsession.getMapper(OrderDao.class);
        UserDao mapperUser = sqlsession.getMapper(UserDao.class);
        GoodsDao mapperGoods = sqlsession.getMapper(GoodsDao.class);


        // 根据 token(nickname)获取 userid，recipient, address, phone
        User user = mapperUser.selectUserByPreciseNickname(addOrderBO.getToken());
        // 根据 goodDetailId(SpecId)获取specName, goodsId, goodsName, unitPrice
        Order order = mapperGoods.selectSpecAndGoodsById(addOrderBO.getGoodsDetailId());
        // 将 user 插入到 order中
        order.setUserId(user.getId());
        order.setNickname(user.getNickname());
        order.setRecipient(user.getRecipient());
        order.setAddress(user.getAddress());
        order.setPhone(user.getPhone());
        // 将 bo其他信息插入到 order中
        order.setNumber(addOrderBO.getNum());
        order.setAmount(addOrderBO.getAmount());
        order.setState(addOrderBO.getState());
        order.setCreateTime(new Date());
        order.setHasComment(false);
        try {
            // 将order插入到 订单表
            int affectedRows = mapperOrder.insertOrder(order);
            System.out.println("order表插入的订单条数为：" + affectedRows);
            sqlsession.commit();
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            sqlsession.rollback();
            return -1;
        } finally {
            sqlsession.close();
        }
    }

    @Override
    public List<GetOrderByStateVO> getOrderByState(Integer state, String nickname) {
        // sql查询四连
        SqlSession sqlsession = MyBatisUtil.getSqlsession();
        OrderDao mapper = sqlsession.getMapper(OrderDao.class);
        // user表和 order表联合查询后，再 goods表和 spec表联合查询
        List<GetOrderByStateVO> orderVOS = mapper.selectOrderByNicknameAndState(state, nickname);
        sqlsession.close();
        return orderVOS;
    }

    @Override
    public Integer settleAccount(SettleAccountBO settleBO) {
        // sql修改七连
        SqlSession sqlsession = MyBatisUtil.getSqlsession();
        OrderDao mapper = sqlsession.getMapper(OrderDao.class);
        List<ChangeOrderBO> cartList = settleBO.getCartList();

        try {
            // 设置state
            Integer affectRows = 0;
            for (ChangeOrderBO cart : cartList) {
                // 表示已经付款，但未发货
                cart.setState(1);
                affectRows += mapper.updateMultiOrder(cart);
            }
            System.out.println("更新订单数为：" + affectRows);
            sqlsession.commit();
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            sqlsession.rollback();
            return -1;
        } finally {
            sqlsession.close();
        }
    }

    @Override
    public Integer changeState(Integer id) {
        // sql修改七连
        SqlSession sqlsession = MyBatisUtil.getSqlsession();
        OrderDao mapper = sqlsession.getMapper(OrderDao.class);
        // 将id包装到 ChangeOrderBO 中
        ChangeOrderBO orderBO = new ChangeOrderBO();
        orderBO.setId(id);
        orderBO.setState(3);    //表示已经收到货
        try {
            Integer affectRows = mapper.updateMultiOrder(orderBO);
            System.out.println("确认收货订单数：" + affectRows);
            sqlsession.commit();
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            sqlsession.rollback();
            return -1;
        } finally {
            sqlsession.close();
        }
    }

    @Override
    public Integer sendComment(CommentBO commentBO) {
        // 插入到 comment表中，再更新order表
        // sql修改七连
        SqlSession sqlsession = MyBatisUtil.getSqlsession();
        OrderDao mapper = sqlsession.getMapper(OrderDao.class);
        // 先获取到 userid
        UserDao mapperUser = sqlsession.getMapper(UserDao.class);
        Integer id = mapperUser.selectIdByNickname(commentBO.getToken());
        commentBO.setUserId(id);
        // 获取到 specName
        GoodsDao mapperGoods = sqlsession.getMapper(GoodsDao.class);
        String specName =  mapperGoods.selectSpecNameById(commentBO.getGoodsDetailId());
        commentBO.setSpecName(specName);
        // 包装到 ChangeOrderBO 中
        ChangeOrderBO orderBO = new ChangeOrderBO();
        orderBO.setId(commentBO.getOrderId());
        orderBO.setHasComment(true);
        try {
            Integer commentAffectedRows = mapper.insertComment(commentBO);
            Integer orderAffectedRows = mapper.updateMultiOrder(orderBO);
            System.out.println("新增评价数：" + commentAffectedRows);
            System.out.println("已经评价订单数：" + orderAffectedRows);
            sqlsession.commit();
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            sqlsession.rollback();
            return -1;
        } finally {
            sqlsession.close();
        }
    }
}




















